package xnet.core
{
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import xnet.Message.ISokcetMessage;
	import xnet.Message.MessageFactory;
	import xnet.SocketManager;
	import xnet.events.SocketEvent;

	/**
	 * 服务提供者 
	 * @author st52
	 * 
	 */	
	public class NetService
	{
		/**Socket实例**/
		private var socket:SocketBase;
		/**主机地址的私有变量**/
		private var _host:String;
		/**端口的私有变量**/
		private var _port:int;
		/**接收到socket进行回调处理**/
		private var resultFunction:Function;
		/**是否已经读取了消息头**/
		private var isReadHead:Boolean = true;
		/**消息的最大长度**/
		private var msgMaxLength:int = 4800;
		/**消息的实际长度**/
		private var msgLength:int;
		/**消息头长度**/
		private var headLength:int = 2;
		/**临时存储byte数组的对象**/
		private var byteArray:ByteArray ;
		
		public function NetService(host:String , port:int)
		{
			_host = host;
			_port = port;
			socket = new SocketBase();
			byteArray = new ByteArray();
			SocketManager.instance.addEventListener(SocketEvent.READY , onResultFunction);
			SocketManager.instance.addEventListener(SocketEvent.RECEIEVED , onReceieveByteArray);
		}
		
		/**建立Socket连接**/
		public function connect():void
		{
			socket.connect(_host , _port);
		}
		
		/**获取当前socket的连接状态**/
		public function get connected():Boolean
		{
			return socket.connected;
		}
		
		/**断开Socket连接**/
		public function close():void
		{
			socket.close();
		}
		/**发送客户端Socket消息
		 **通过ByteArray,启用
		 */
		public function send(byteArray:ByteArray , rsFunction:Function):void
		{
			if(!socket.connected)
			{
				return;
			}
			if(rsFunction!=null)
			{
				resultFunction = rsFunction;
			}
			socket.writeBytes(byteArray);
			socket.flush();
		}
		/**处理指令工厂的回调数据**/
		private function onResultFunction(event:SocketEvent):void
		{
			var cmd:int = event.data.cmd;
			var socketCommand:ISokcetMessage = MessageFactory.getCommandByType(cmd);
			resultFunction.call(resultFunction , socketCommand);
		}
		
		private function onReceieveByteArray(event:SocketEvent = null):void
		{
			// var cmd:int= socket.readByte();
             byteArray.position = 0;
			// socket.readBytes(byteArray , 0 , msgLength);
			 socket.readBytes(byteArray);
			 MessageFactory.decodeSocketData(byteArray);
		}
	}
}